const isSameType = (val1: unknown, val2: unknown) => Object.prototype.toString.call(val1) === Object.prototype.toString.call(val2);

/** 将一个数据序列化为字符串 */
export function safeParse<T>(jsonStr: string, defaultValue: T): T;
export function safeParse<T>(jsonStr: string): T | undefined;
export function safeParse<T>(jsonStr: string, defaultValue?: T) {
  let value: T;
  try {
    value = JSON.parse(jsonStr);
    if (defaultValue && !isSameType(value, defaultValue)) {
      return defaultValue;
    }

    return value;
  } catch (error) {
    // 处理字符串的情况，将源数据返回
    value = jsonStr as T;
  }

  return value !== undefined ? value : defaultValue;
}
